﻿'No copyright, feel free to use as you see fit - Jonathan Allen

Imports ClrExtensions
Imports WrapNetflix
Imports ClrExtensions.Net.Rest

Module Module1

	Sub Main()
		TryRead("Consumer Key", My.Settings.ConsumerKey)
		TryRead("Consumer Secret", My.Settings.ConsumerSecret)

		My.Settings.Save()
		Dim con As New NetflixConnection(My.Settings.ConsumerKey, My.Settings.ConsumerSecret)

		Dim needNewToken = My.Settings.UserId = Nothing
		If Not needNewToken Then
			Console.Write("Login as [" & My.Settings.UserId & "]? [Y] ")
			If Console.ReadLine.StartsWith("N", StringComparison.CurrentCultureIgnoreCase) Then
				needNewToken = True
			Else
				Console.WriteLine(My.Settings.AccessToken)
				Console.WriteLine(My.Settings.AccessTokenSecret)
			End If
		End If

		Dim access As AccessToken
		If needNewToken Then
			Dim request As RequestToken
			Try
				request = con.GenerateRequestToken
			Catch ex As Exception
				Console.WriteLine("Unable to generate request token: " & ex.Message)
				Console.ReadLine()
				Return
			End Try

			Process.Start(request.PermissionUrl)

			Console.WriteLine("Press Enter once you have approved the loging request")
			Console.ReadLine()

			Try
				access = request.ConvertToAccessToken
			Catch ex As Exception
				Console.WriteLine("Unable to generate access token: " & ex.Message)
				Console.ReadLine()
				Return
			End Try

			My.Settings.UserId = access.UserId
			My.Settings.AccessToken = access.Token
			My.Settings.AccessTokenSecret = access.TokenSecret
			My.Settings.Save()
		Else
			access = New AccessToken(My.Settings.UserId, My.Settings.AccessToken, My.Settings.AccessTokenSecret)
		End If

		Dim action As String = Nothing
		Dim searchText As String = Nothing
		Dim startIndex As Integer?
		Dim maxResults As Integer? = 50
		Dim itemsPerPage As Integer?
		Dim titleID As String = Nothing

		Dim user = New User(access, con)

		Do
			Console.WriteLine()
			Console.WriteLine()
			Console.WriteLine("1: Autocomplete Search")
			Console.WriteLine("2: Title Search - Minimal")
            Console.WriteLine("3: Title Search - Full Property Check")
            Console.WriteLine("4: Fetch Title by ID")
            Console.WriteLine()
            Console.WriteLine("11: Display Queue")
            Console.WriteLine("12: Add Item to Queue")
            Console.WriteLine("13: Remove Item from Queue")
            Console.WriteLine()
            Console.WriteLine("21: Display Instant Queue")
            Console.WriteLine("22: Add Item to Instant Queue")
            Console.WriteLine("23: Remove Item from Instant Queue")
            Console.WriteLine()
            Console.WriteLine("30: Rental History All")
            Console.WriteLine("31: Rental History Shipped")
            Console.WriteLine("32: Rental History Returned")
            Console.WriteLine("33: Rental History Watched")
            Console.WriteLine()

            Console.WriteLine("0: Exit")
			TryRead("Action", action)
			Console.WriteLine()


			Try
				Select Case action
					Case "1"
						TryRead("Search phrase", searchText)
						Console.WriteLine()

						Dim runningStartIndex = If(startIndex, 0)
						Dim list = con.Catalog.TitlesForAutocomplete(searchText)
						For Each item In list
							Console.WriteLine(vbTab & item)
						Next

					Case "2"
						TryRead("Search phrase", searchText)
						TryRead("Max Results", maxResults)
						Console.WriteLine()

						Dim entries = con.Catalog.TitleSearch(searchText, maxResults.Value)
						Dim types As New List(Of String)
						For Each item In entries
							Console.WriteLine(item.GetType.FullName)
							Console.WriteLine(vbTab & item.Title)
							Console.WriteLine(vbTab & item.Id)
						Next

					Case "3"
						TryRead("Search phrase", searchText)
						TryRead("Max Results", maxResults)
						Console.WriteLine()

						Dim entries = con.Catalog.TitleSearch(searchText, maxResults.Value)

						For Each item In (From e In entries Order By e.Title)
							Console.WriteLine(item.Title)
							Console.WriteLine(vbTab & item.Id)
							Console.WriteLine(vbTab & "Type: " & item.GetType.FullName)

                            If item.DiscsLink IsNot Nothing Then
                                Dim discs = item.DiscsLink.GetCatalogTitles(True) ' DirectCast(item, IResourceWithDiscs).Discs
                                If discs.Count > 0 Then
                                    For Each disc In discs
                                        Console.WriteLine(vbTab & "Disc: " & disc.Title)
                                        Console.WriteLine(vbTab & vbTab & disc.Id)
                                    Next
                                End If
                            End If
							Console.WriteLine()
							Console.WriteLine()

							PrintTitleProperties(item)
							Console.WriteLine()
							Console.WriteLine()

						Next

                    Case "4"
                        Dim id As String
                        TryRead("Title id", id)
                        If id IsNot Nothing Then
                            Dim title = con.Catalog.GetTitle(id)
                            PrintTitleProperties(title)
                        End If

                    Case "11"
                        Console.WriteLine("Queue")

                        user.DiscQueue.Refresh()

                        For Each item In user.DiscQueue
                            Console.WriteLine(item.Position & ": " & item.Title)
                        Next
                        Dim position As Integer?
                        Do
                            TryRead("Examine title? (0 to exit)", position)
                            If position > 0 Then
                                Dim title = user.DiscQueue.ItemByPosition(position.Value)
                                If title IsNot Nothing Then
                                    PrintTitleProperties(title)
                                End If
                            Else : Exit Do
                            End If
                        Loop

                    Case "12"
                        Dim titleToAdd As Integer?

                        TryRead("Search phrase", searchText)
                        Console.WriteLine()

                        Dim entries = con.Catalog.TitleSearch(searchText, 10)
                        For i As Integer = 0 To entries.Count - 1 Step 1
                            Console.WriteLine(i + 1 & ": " & entries(i).Title)
                        Next
                        Console.WriteLine("0: Exit")
                        TryRead("Add Title? ", titleToAdd)

                        If titleToAdd > 0 Then
                            user.DiscQueue.Add(entries(titleToAdd.Value - 1))

                            Console.WriteLine()
                            Console.WriteLine("New Queue")
                            For Each item In user.DiscQueue
                                Console.WriteLine(item.Position & ": " & item.Title)
                            Next


                        End If

                    Case "14"
                        Console.WriteLine("Enter title id")
                        Dim id = Console.ReadLine
                        user.DiscQueue.Add(id)

                        Console.WriteLine()
                        Console.WriteLine("New Queue")
                        For Each item In user.DiscQueue
                            Console.WriteLine(item.Position & ": " & item.Title)
                        Next

                    Case "21"
                        Console.WriteLine("Instant Queue")

                        user.InstantQueue.Refresh()

                        For Each item In user.InstantQueue
                            Console.WriteLine(item.Position & ": " & item.Title)
                        Next
                        Dim position As Integer?
                        Do
                            TryRead("Examine title? (0 to exit)", position)
                            If position > 0 Then
                                Dim title = user.InstantQueue.ItemByPosition(position.Value)
                                If title IsNot Nothing Then
                                    PrintTitleProperties(title)
                                End If
                            Else : Exit Do
                            End If

                        Loop

                    Case "22"
                        Dim titleToAdd As Integer?

                        TryRead("Search phrase", searchText)
                        Console.WriteLine()

                        Dim entries = con.Catalog.TitleSearch(searchText, 10)
                        For i As Integer = 0 To entries.Count - 1 Step 1
                            Console.WriteLine(i + 1 & ": " & entries(i).Title)
                        Next
                        Console.WriteLine("0: Exit")
                        TryRead("Add Title? ", titleToAdd)

                        If titleToAdd > 0 Then
                            user.InstantQueue.Add(entries(titleToAdd.Value - 1))

                            Console.WriteLine()
                            Console.WriteLine("New Queue")
                            For Each item In user.InstantQueue
                                Console.WriteLine(item.Position & ": " & item.Title)
                            Next
                        End If

                    Case "23"
                        Console.WriteLine("Instant Queue")

                        user.InstantQueue.Refresh()

                        For Each item In user.InstantQueue
                            Console.WriteLine(item.Position & ": " & item.Title)
                        Next
                        Dim position As Integer?

                        TryRead("Delete title? (0 to exit)", position)
                        If position > 0 Then
                            Dim title = user.InstantQueue.ItemByPosition(position.Value)
                            user.InstantQueue.Remove(title)

                            Console.WriteLine()
                            Console.WriteLine("New Queue")
                            For Each item In user.InstantQueue
                                Console.WriteLine(item.Position & ": " & item.Title)
                            Next
                        End If


                    Case "30", "31", "32", "33"
                        TryRead("Max Results", maxResults)
                        Console.WriteLine()

                        Dim mode As RentalHistoryType = CType(CInt(action) - 30, RentalHistoryType)

                        Dim entries = user.GetRentalHistory(mode, maxResults.Value)
                        Dim types As New List(Of String)
                        For Each item In entries
                            Console.WriteLine(item.GetType.FullName)
                            Console.WriteLine(vbTab & item.Title)
                            Console.WriteLine(vbTab & item.Id)
                        Next


                    Case "0"
                        Exit Do

                End Select
            Catch ex As Exception
                Console.WriteLine()
                Console.WriteLine("Action failed!")
                Console.WriteLine(ex)
            End Try
        Loop

        '		Do

        '			Console.WriteLine()
        '			Console.WriteLine("1: Title Search")
        '			Console.WriteLine("2: Autocomplete Search")
        '			Console.WriteLine("3: Title Index Dump")
        '			Console.WriteLine("4: Title Property Check")
        '			Console.WriteLine("5: Walk the Title Index, grabbing the full titles")
        '			Console.WriteLine("6: Get all the RSS feeds that are specific to the user")

        '			Console.WriteLine("10: Get the queue")
        '			Console.WriteLine("11: Add an item to an queue")
        '			Console.WriteLine("12: Remove an item to an queue")

        '			Console.WriteLine("20: Get the instant queue")
        '			Console.WriteLine("21: Add an item to an instant queue")
        '			Console.WriteLine("22: Remove an item to an instant queue")

        '			Console.WriteLine("101: Schema Check")

        '			Console.WriteLine("0: Exit")
        '			TryRead("Action", action)
        '			Console.WriteLine()

        '			Try
        '				Select Case action

        '					Case "0"
        '						Return

        '					Case "1"
        '						TryRead("Search phrase", searchText)
        '						TryRead("Start index", startIndex)
        '						TryRead("Max Records per page", maxResults)
        '						TryRead("Number of Pages", numOfPages)
        '						Console.WriteLine()

        '						Dim runningStartIndex = If(startIndex, 0)
        '						For page = 1 To If(numOfPages, 1)
        '							Dim list = con.Catalog.TitleSearchByPage(searchText, runningStartIndex, maxResults)
        '							Console.WriteLine("Page " & page)
        '							Console.WriteLine(vbTab & "StartIndex: " & list.StartIndex)
        '							Console.WriteLine(vbTab & "ResultsPerPage: " & list.ResultsPerPage)
        '							Console.WriteLine(vbTab & "NumberOfResults: " & list.NumberOfResults)
        '							runningStartIndex += list.ResultsPerPage
        '						Next

        '					Case "2"
        '						TryRead("Search phrase", searchText)
        '						Console.WriteLine()

        '						Dim runningStartIndex = If(startIndex, 0)
        '						Dim list = con.Catalog.TitlesForAutocomplete(searchText)
        '						For Each item In list
        '							Console.WriteLine(vbTab & item)
        '						Next

        '					Case "3"
        '						Console.WriteLine("This takes a really, really long time. Are you sure you want to do this? (Yes|No)")
        '						If Console.ReadLine = "Yes" Then
        '							Console.WriteLine("Dumping full index to c:\temp\index.xml")

        '							con.Catalog.DownloadIndex("c:\temp\index.xml")

        '							Console.WriteLine("Done")
        '						End If

        '					Case "4"
        '						TryRead("Search phrase", searchText)
        '						TryRead("Max Records", maxResults)

        '						Dim list = con.Catalog.TitleSearch(searchText, maxResults.Value)

        '						For Each title In list
        '							Console.Clear()
        '							Console.WriteLine("Search Result")
        '							PrintTitleProperties(title)

        '							Console.Clear()
        '							Console.WriteLine("Expansion: None")
        '							Dim details = title.GetDetails(TitleExpansions.None)
        '							PrintTitleProperties(details)


        '							Console.Clear()
        '							Console.WriteLine("Link: Cast")
        '							Dim cast = con.RequestResource(title.CastLink)
        '							Console.WriteLine(cast)
        '							Console.ReadLine()

        '							Console.Clear()
        '							Console.WriteLine("Expansion: Cast")
        '							Dim cast2 = title.GetDetails(TitleExpansions.Cast)
        '							PrintTitleProperties(cast2)

        '							Console.Clear()
        '							Console.WriteLine("Expansion: All")
        '							Dim similars2 = title.GetDetails(TitleExpansions.All)
        '							PrintTitleProperties(similars2)

        '						Next


        '					Case "5"
        '						Console.WriteLine("Warning! If you do this you WILL exceed your daily request limit and be LOCKED OUT of your account for 24 hours. Are you sure you want to do this? (Yes|No)")
        '						If Console.ReadLine = "Yes" Then
        '							Dim index = XDocument.Load("c:\temp\index.xml")

        '							Console.WriteLine(index.Nodes.Count)
        '							Console.WriteLine(index.Root.Nodes.Count)
        '							IO.Directory.CreateDirectory("c:\temp\movies")

        '							For Each node In index.Root.<title_index_item>
        '								Dim title = node.<title>.Value
        '								Dim id = node.<id>.Value
        '								Console.Write(title & vbTab & id & "... ")
        '								Dim fileName As String = "c:\temp\movies\" & ClrExtensions.IOExtension.ToFileName(title) & ".xml"
        '								If Not IO.File.Exists(fileName) Then
        'retry:
        '									Try
        '										Dim details = con.Catalog.GetTitleDetails(id, TitleExpansions.All)
        '										details.Source.Save(fileName)
        '										Console.WriteLine("saved!")
        '									Catch ex As RequestFrequencyException
        '										Console.Write("retrying... ")
        '										Threading.Thread.Sleep(1000)
        '										GoTo retry
        '									Catch ex As NotFoundException
        '										Console.WriteLine("not found.")
        '									End Try
        '								Else
        '									Console.WriteLine("skiped")
        '								End If
        '							Next

        '							Console.WriteLine("Done")
        '						End If
        '					Case "6"
        '						'TODO - Move this into the User object.
        '						Dim feedsRaw = con.RequestResource(NetflixUrls.GetUsersFeeds(access.UserId), access)
        '						Console.WriteLine(feedsRaw)




        '					Case "10" 'view instant
        '						TryRead("Max Records", maxResults)

        '						Dim xml = user.DiscQueue.GetTitles(QueueSortOrder.QueueSequence, maxResults)
        '						Console.WriteLine(xml.ToString)



        '					Case "11" 'add instant
        '						TryRead("Title ID", titleID)

        '						user.DiscQueue.AddTitle(titleID)



        '					Case "12" 'delete instant


        '						TryRead("Title ID", titleID)

        '						user.DiscQueue.DeleteTitle(titleID)




        '					Case "20" 'view instant
        '						TryRead("Max Records", maxResults)

        '						Dim xml = user.InstantQueue.GetTitles(QueueSortOrder.QueueSequence, maxResults)
        '						Console.WriteLine(xml.ToString)



        '					Case "21" 'add instant
        '						TryRead("Title ID", titleID)

        '						user.InstantQueue.AddTitle(titleID)



        '					Case "22" 'delete instant


        '						TryRead("Title ID", titleID)

        '						user.InstantQueue.DeleteTitle(titleID)








        '					Case "101"

        '						Try
        '							Dim x = con.RequestResource(New RestCall(RestVerb.Get, "http://api.netflix.com/categories/genres"))
        '							Console.WriteLine(x)
        '						Catch ex As Exception
        '							Console.WriteLine(ex.ToString)
        '						End Try

        '						Console.ReadLine()

        '						Try
        '							Dim y = con.RequestResource(New RestCall(RestVerb.Get, "http://api.netflix.com/catalog/genres"))
        '							Console.WriteLine(y)
        '						Catch ex As Exception
        '							Console.WriteLine(ex.ToString)
        '						End Try
        '				End Select

        '			Catch ex As Exception
        '				Console.WriteLine()
        '				Console.WriteLine("Action failed!")
        '				Console.WriteLine(ex)

        '			End Try

        '		Loop





        'Console.WriteLine()
        'Console.WriteLine()
        'Console.WriteLine()


        'Dim list = con.Catalog.TitleSearch("James Bond")
        '      Console.WriteLine("Number of Results: " & list.NumberOfResults)
        '      Console.WriteLine("StartIndex: " & list.StartIndex)
        'Console.WriteLine("ResultsPerPage: " & list.ResultsPerPage)
        '      For Each item In list
        '          Console.WriteLine(item.TitleShort & vbTab & item.Title)
        '      Next
        '      Console.ReadLine()

        'For Each item In con.Catalog.TitlesForAutocomplete("Roman E", 0, 100)
        '	Console.WriteLine(item)
        'Next


        'Console.WriteLine("Dumping full index to disk")

        'Using incomingStream = con.Catalog.TitlesIndexRaw
        '	Using file = New IO.StreamWriter(IO.File.OpenWrite("c:\temp\index.xml"))
        '		Dim s = incomingStream.ReadLine
        '		Do Until s Is Nothing
        '			file.WriteLine(s)
        '			s = incomingStream.ReadLine
        '		Loop
        '	End Using
        'End Using

        Console.WriteLine("Done")
        Console.ReadLine()

	End Sub

	Private Sub PrintTitleProperties(ByVal title As CatalogTitle)
		Console.WriteLine(title.Source)
		Console.WriteLine()
		WriteLine("AverageRating", title.AverageRating)
		WriteLine("AwardsLink", title.AwardsLink)
		WriteLine("BoxArt L", title.BoxArt(BoxArtSize.Large))
		WriteLine("BoxArt M", title.BoxArt(BoxArtSize.Medium))
		WriteLine("BoxArt S", title.BoxArt(BoxArtSize.Small))
		WriteLine("CastLink", title.CastLink)
		WriteLine("DirectorsLink", title.DirectorsLink)
		WriteLine("Discs", title.DiscsLink)
		WriteLine("EpisodesLink", title.EpisodesLink)
		WriteLine("FormatsLink", title.FormatsLink)
		WriteLine("FullTitle", title.Title)
		WriteLine("Genres", title.Genres)
		WriteLine("Id", title.Id)
		WriteLine("LanguagesAndAudioLink", title.LanguagesAndAudioLink)
		WriteLine("Link Names", title.LinkNames)
		WriteLine("MPAA Ratings", title.MpaaRatings)
		WriteLine("OfficialWebpageLink", title.OfficialWebpageLink)
		WriteLine("ReleaseYear", title.ReleaseYear)
		WriteLine("Runtime", title.Runtime)
		WriteLine("ScreenFormatsLink", title.ScreenFormatsLink)
		WriteLine("SeriesLink", title.SeriesLink)
		WriteLine("ShortTitle", title.ShortTitle)
		WriteLine("SimilarsLink", title.SimilarsLink)
		WriteLine("SynopsisLink", title.SynopsisLink)
		WriteLine("TvRatings", title.TvRatings)
		WriteLine("WebpageLink", title.WebpageLink)
		Console.ReadLine()
	End Sub

	Sub TryRead(ByVal label As String, ByRef target As String)
		Console.Write(label & "? ")
		If target <> "" Then Console.Write("[" & target & "] ")
		Dim temp = Console.ReadLine()
		If temp <> "" Then target = temp
	End Sub

	Sub TryRead(ByVal label As String, ByRef target As Integer?)
		Console.Write(label & "? ")
		If target.HasValue Then Console.Write("[" & target & "] ")
		Dim temp = Console.ReadLine()
		If temp <> "" Then target = CInt(temp)
	End Sub

	Sub WriteLine(ByVal name As String, ByVal value As Object)
		If value IsNot Nothing Then
			Console.WriteLine(name & ": " & value.ToString)
		Else
			Console.WriteLine(name & ": <NULL>")
		End If
	End Sub

	Sub WriteLine(ByVal name As String, ByVal value As String)
		If value IsNot Nothing Then
			Console.WriteLine(name & ": " & value)
		Else
			Console.WriteLine(name & ": <NULL>")
		End If
	End Sub

	Sub WriteLine(Of T As Structure)(ByVal name As String, ByVal value As Nullable(Of T))
		If value.HasValue Then
			Console.WriteLine(name & ": " & value.Value.ToString)
		Else
			Console.WriteLine(name & ": <NULL>")
		End If
	End Sub

	Sub WriteLine(Of T)(ByVal name As String, ByVal list As IList(Of T))
		If list.Count = 0 Then
			Console.WriteLine(name & ": <Empty>")
		Else
			Console.WriteLine(name & ": " & (From item In list Select text = item.ToString).ToList.Join(","))
		End If
	End Sub





End Module
